/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package shmallarchitect.jpa.controllers;

import java.util.List;
import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.transaction.UserTransaction;
import shmallarchitect.jpa.controllers.exceptions.IllegalOrphanException;
import shmallarchitect.jpa.controllers.exceptions.NonexistentEntityException;
import shmallarchitect.jpa.controllers.exceptions.RollbackFailureException;
import shmallarchitect.jpa.entities.Gallery;
import java.util.HashSet;
import java.util.Set;
import java.util.ArrayList;
import shmallarchitect.jpa.entities.User;

/**
 *
 * @author jaccus
 */
public class UserJpaController {
    @Resource(mappedName="utx")
    private UserTransaction utx = null;
    @PersistenceUnit(unitName = "ShmallArchitectPU")
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(User user) throws RollbackFailureException, Exception {
        if (user.getGalleries() == null) {
            user.setGalleries(new HashSet<Gallery>());
        }
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Set<Gallery> attachedGalleries = new HashSet<Gallery>();
            for (Gallery galleriesGalleryToAttach : user.getGalleries()) {
                galleriesGalleryToAttach = em.getReference(galleriesGalleryToAttach.getClass(), galleriesGalleryToAttach.getId());
                attachedGalleries.add(galleriesGalleryToAttach);
            }
            user.setGalleries(attachedGalleries);
            em.persist(user);
            for (Gallery galleriesGallery : user.getGalleries()) {
                User oldUserOfGalleriesGallery = galleriesGallery.getUser();
                galleriesGallery.setUser(user);
                galleriesGallery = em.merge(galleriesGallery);
                if (oldUserOfGalleriesGallery != null) {
                    oldUserOfGalleriesGallery.getGalleries().remove(galleriesGallery);
                    oldUserOfGalleriesGallery = em.merge(oldUserOfGalleriesGallery);
                }
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(User user) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            User persistentUser = em.find(User.class, user.getId());
            Set<Gallery> galleriesOld = persistentUser.getGalleries();
            Set<Gallery> galleriesNew = user.getGalleries();
            List<String> illegalOrphanMessages = null;
            for (Gallery galleriesOldGallery : galleriesOld) {
                if (!galleriesNew.contains(galleriesOldGallery)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain Gallery " + galleriesOldGallery + " since its user field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            Set<Gallery> attachedGalleriesNew = new HashSet<Gallery>();
            for (Gallery galleriesNewGalleryToAttach : galleriesNew) {
                galleriesNewGalleryToAttach = em.getReference(galleriesNewGalleryToAttach.getClass(), galleriesNewGalleryToAttach.getId());
                attachedGalleriesNew.add(galleriesNewGalleryToAttach);
            }
            galleriesNew = attachedGalleriesNew;
            user.setGalleries(galleriesNew);
            user = em.merge(user);
            for (Gallery galleriesNewGallery : galleriesNew) {
                if (!galleriesOld.contains(galleriesNewGallery)) {
                    User oldUserOfGalleriesNewGallery = galleriesNewGallery.getUser();
                    galleriesNewGallery.setUser(user);
                    galleriesNewGallery = em.merge(galleriesNewGallery);
                    if (oldUserOfGalleriesNewGallery != null && !oldUserOfGalleriesNewGallery.equals(user)) {
                        oldUserOfGalleriesNewGallery.getGalleries().remove(galleriesNewGallery);
                        oldUserOfGalleriesNewGallery = em.merge(oldUserOfGalleriesNewGallery);
                    }
                }
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Long id = user.getId();
                if (findUser(id) == null) {
                    throw new NonexistentEntityException("The user with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Long id) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            User user;
            try {
                user = em.getReference(User.class, id);
                user.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The user with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            Set<Gallery> galleriesOrphanCheck = user.getGalleries();
            for (Gallery galleriesOrphanCheckGallery : galleriesOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This User (" + user + ") cannot be destroyed since the Gallery " + galleriesOrphanCheckGallery + " in its galleries field has a non-nullable user field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            em.remove(user);
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<User> findUserEntities() {
        return findUserEntities(true, -1, -1);
    }

    public List<User> findUserEntities(int maxResults, int firstResult) {
        return findUserEntities(false, maxResults, firstResult);
    }

    private List<User> findUserEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            Query q = em.createQuery("select object(o) from User as o");
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public User findUser(Long id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(User.class, id);
        } finally {
            em.close();
        }
    }

    public int getUserCount() {
        EntityManager em = getEntityManager();
        try {
            return ((Long) em.createQuery("select count(o) from User as o").getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }

}
